package com.ithinks.flow.common.utils.middleware.rabbitMQ.simpleQueue;

import com.ithinks.flow.common.utils.middleware.rabbitMQ.ConnectionUtils;
import com.rabbitmq.client.*;
import java.io.IOException;

/**
 * @Description 简单队列消费者
 * @ClassName SimpleQueueConsumer
 * @Author MR.LI
 * @date 2020.11.26 13:23
 */
public class SimpleQueueConsumer {

    /**
     * 接收端操作流程
     * 1、创建连接
     * 2、创建通道
     * 3、声明队列
     * 4、监听队列
     * 5、接收消息
     */
    //队列名称
    private static String QUEUE_NAME = "hello1";
    //主机IP
    private static String IP = "localhost";
    //端口
    private static int PORT = 5672;
    //虚拟机IP，默认/
    private static String VHOST = "/";
    //队列名称
    private static String USERNAME = "guest";

    private static String PASSWORD = "guest";

    public static void main(String[] args) {

        Connection connection = ConnectionUtils.getConnection(IP,PORT,VHOST,USERNAME,PASSWORD);
        try {
            Channel channel = connection.createChannel();
            channel.queueDeclare(QUEUE_NAME,false,false,false,null);
            DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    super.handleDelivery(consumerTag, envelope, properties, body);
                    String exchange = envelope.getExchange();

                    String routerKey = envelope.getRoutingKey();

                    long deliveryTag = envelope.getDeliveryTag();

                    String msg = new String(body,"UTF-8");

                    System.out.println("recive Message :" + msg);
                }
            };

            channel.basicConsume(QUEUE_NAME,true,defaultConsumer);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

        }

    }
}
